package com.google.code.openperfmon.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hibernate.Session;

import com.google.code.openperfmon.db.DBManager;
import com.google.code.openperfmon.domain.MonitorInstance;

public class MonitorInstanceDAO extends UniversalDAO<MonitorInstance> {
	public MonitorInstanceDAO() {
		super(MonitorInstance.class);
	}
	
	@SuppressWarnings("unchecked")
	public Map<Long, Integer> getInstanceCountsByDefinitionIds(List<Long> defIds) {
		return countsByIds(
			DBManager.get().createSQLQuery(
				"select d.id, count(i.id) as cnt " +
				"from MonitorDefinition d " +
				"join MonitorInstance i on i.definition_id = d.id " +
				"where d.id in (:ids) " +
				"group by d.id")
				.addScalar("id", Hibernate.LONG)
				.addScalar("cnt", Hibernate.INTEGER)
				.setParameterList("ids", defIds)
				.list());
	}
	
	@SuppressWarnings("unchecked")
	public Map<Long, Integer> getInstanceCountsByHostIds(List<Long> hostIds) {
		return countsByIds(
			DBManager.get().createSQLQuery(
				"select h.id, count(i.id) as cnt " +
				"from Host h " +
				"join MonitorInstance i on i.host_id = h.id " +
				"where h.id in (:ids) " +
				"group by h.id")
				.addScalar("id", Hibernate.LONG)
				.addScalar("cnt", Hibernate.INTEGER)
				.setParameterList("ids", hostIds)
				.list());
	}
	
	public void deleteByHostId(Long hostId) {
		Session ses = DBManager.get();
		ses.createQuery(
				"delete from MonitorInstance i where i.host.id = :id")
				.setLong("id", hostId)
				.executeUpdate();
		ses.flush();
	}
}
